#include <iostream>
#include <fstream>
#include <sstream>

#include "server/Dictionary.h"
#include "client/Configuration.h"

using std::ifstream;
using std::istringstream;
using std::cout;
using std::cerr;

Dictionary *Dictionary::_instance = nullptr;

Dictionary::Dictionary(){

}

Dictionary *Dictionary::createInstance(){
    if(!_instance)
        _instance = new Dictionary();
    
    return _instance;
}

void Dictionary::init(const string &dictpath, const string &indexpath){
    ifstream ifs_dict(dictpath);
    ifstream ifs_index(indexpath);

    if(!ifs_dict.is_open() || !ifs_index.is_open()){
        cerr << (!ifs_dict.is_open() ? "dictionary open failed" : "") << '\n'
             << (!ifs_index.is_open() ? "words index open failed" : "");
    }
    cout << dictpath << "open success" << '\n';
    cout << indexpath << "open success" << '\n';

    //预热
    char word[1024];
    pair<string, int> word_pair;
    while (ifs_dict.getline(word, 1024)){
        istringstream iss(word);
        iss >> word_pair.first;
        iss >> word_pair.second;

        _dict.push_back(word_pair);
    }

    string line;
    while (std::getline(ifs_index, line)){
        istringstream iss(line);
        string word_index;
        iss >> word_index;
        int index;
        while(iss >> index){
            _index[word_index].insert(index);
        }
    }
}

vector<pair<string, int>> &Dictionary::getDict(){
    return _dict;
}
map<string, set<int>> &Dictionary::getIndexTable(){
    return _index;
}

int Dictionary::doQuery(const string &key){
    for(auto &i: _dict){
        if(i.first == key){
            return i.second;
        }
    }
    return 0;
}